package com.laowang.blog.controller;

import com.laowang.blog.dto.AccessTokenDto;
import com.laowang.blog.dto.GiteeUser;
import com.laowang.blog.mapper.UserMapper;
import com.laowang.blog.model.User;
import com.laowang.blog.provider.GiteeProvider;
import com.laowang.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.HandshakeResponse;
import java.util.UUID;

@Controller
public class AuthorizeController {
    @Autowired
    private AccessTokenDto accessTokenDto;

    @Autowired
    private GiteeProvider giteeProvider;

    @Autowired
    private GiteeUser giteeUser;

    @Value("${gitee.client.id}")
    private String clientId;

    @Value("${gitee.client.secret}")
    private String clientSecret;

    @Value("${gitee.redirect.uri}")
    private String uri;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                            HttpServletRequest request,
                            HttpServletResponse response){
        accessTokenDto.setClient_id(clientId);
        accessTokenDto.setClient_secret(clientSecret);
        accessTokenDto.setRedirect_url(uri);
        accessTokenDto.setCode(code);
        accessTokenDto.setState(state);
        String Token = giteeProvider.getAccessToken(accessTokenDto);
        giteeUser = giteeProvider.getUser(Token);
        if(giteeUser !=null){
            User user=new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token",token));
            request.getSession().setAttribute("user", giteeUser);
            return "redirect:/";
        }else{
            return "redirect:/";
        }
    }

    @GetMapping("logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie=new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
